package com.acme.bankapp.server;

import java.io.*;
import java.net.*;
import java.util.*;

public class BankClient {
	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	Scanner scan = new Scanner(System.in);
	String message;
	
	void run() {
		try {
			requestSocket = new Socket("localhost", 1234);
			System.out.println("connected to localhost in port 1234");
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			in  = new ObjectInputStream(requestSocket.getInputStream());
			try {
				message = (String)in.readObject();
				System.out.println("server>" + message);
				sendMessage("Hi my server!");
			} catch (ClassNotFoundException cnf) {
				cnf.printStackTrace();
			}
			do {
				message = scan.nextLine();
				sendMessage(message);
			} while (!message.equals("bye"));
		} catch (UnknownHostException uhe) {
			System.err.println("You are trying to connect to unknown host!");
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
	
	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		BankClient client = new BankClient();
		client.run();
	}

}
